<template>
  <div>
    <Card>
      <div class="p-relative">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn">
            <Button type="warning" @click='create'>添加场地</Button>
          </div>
          <div class="flex-item">
            <Input v-model="searchObj.name" placeholder="请输入门店或场地名称"></Input>
          </div>

          <div class="flex-item search-btn" @click="search">
            <Button type="warning">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="reset">
            <Button>重置</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top"> <area shape="is_sheet" coords="" href="" alt="" />
        <template slot-scope="{ row, index }" slot="amount">
          {{row.amount}}元/小时
        </template>
        <template slot-scope="{ row, index }" slot="is_sheet">
          {{row.is_sheet==1?'多用':'单用'}}
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='warning' @click="detail(row, index)" size='small'>管理</Button>
            <Button type='warning' @click="edit(row, index)" size='small'>编辑</Button>
            <Button type='error' @click="del(row, index)" size='small'>删除</Button>

          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>

    <!-- 添加弹窗 -->
    <Modal v-model="createModal" :title="createTitle" width='1000'>

      <Tabs value="veneu1" v-model="veneuAmount">
        <TabPane label="场地信息" name="veneu1">
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
            <FormItem label="选择门店" prop="store_id">
              <Select v-model="formValidate.store_id" placeholder="请选择选择门店" @on-change="getStoreVenueNumber">
                <Option v-for="item in data.storeList" :value="item.id" :key="item.id">{{item.name}}</Option>
              </Select>

            </FormItem>

            <FormItem label="项目分类">
              <CheckboxGroup v-model="formValidate.category_id">
                <Checkbox :label="item.id" v-for="(item,index) in data.categoryList">{{item.name}}</Checkbox>

              </CheckboxGroup>
              <!-- <Input v-model="formValidate.name" placeholder="请输入球场名称"></Input> -->
            </FormItem>
            <!--   <FormItem label="球场数量" prop="num">
                    <Input v-model="formValidate.num" placeholder="请输入球场数量"></Input>
                  </FormItem>-->

            <FormItem label="添加场地编号" style="margin-bottom: 5px;">
              <Input placeholder="输入场地编号" v-model="setNumber" style="width:100px;text-align: center;"> </Input><Button
                @click="setVenueNumber" type="warning">添加</Button>

            </FormItem>
            <FormItem label="">
              <div v-for="item in formValidate.number"
                style="display: inline-block; margin-right: 10px;margin-bottom: 5px;">
                <Input :value="item+'号场'" disabled style="width:60px;text-align: center; color: #000000 !important">
                </Input><Button type="error" style="padding: 5px ;" @click="delVenueNumber(item)" ghost>X</Button>
              </div>

            </FormItem>
            <FormItem label="是否开启">
              <RadioGroup v-model="formValidate.status">
                <Radio label="1">开启</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
                <Radio label="0">关闭</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
              </RadioGroup>
            </FormItem>

          </Form>
        </TabPane>
        <TabPane label="场地费用" name="veneu2">
          <!-- 批量 -->

            <div class="fee-box" style="width: 98%;" >
              <div class="fee-head">
                <span>批量设置</span>
                <Button type="warning" class="fee-add" size="small" @click='batchInsert'>新增</Button>
                <Button type="info" class="fee-batch" size="small" @click='batchSet'>批量设置</Button>
              </div>
              <div style="padding:5px 15px  ">
                <Row :gutter="16" v-for="(item,index) in batchLen">
                  <Col span="5">
                  <TimePicker type="timerange" :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options format="HH:mm"
                    @on-change="batchAddTime($event,index)"  placeholder="请选择时间段"
                    style="width: 100%">
                  </TimePicker>
                  </Col>
                  <Col span="5">
                  <Input @on-keyup="batchAddAmount($event,index)"   type="number"
                    placeholder="请设置场地费用"> <span slot="append">元/小时</span></Input>

                  </Col>

                </Row>

              </div>
            </div>

          <div class="flex-box flex-fee">
            <div class="fee-box" v-for="(item,index) in weekArr">
              <div class="fee-head">
                <span>{{item.name}}</span>
                <Button type="warning" class="fee-add" size="small" @click='weekInsert(item,index)'>新增</Button>
              </div>
              <div style="padding:5px 15px  ">

                <Row :gutter="16" v-if="item.time_range.length>0" v-for="(row,j) in item.time_range">
                 <Col span="11">
                 <TimePicker type="timerange" :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options format="HH:mm"
                   @on-change="weekAddTime($event,item,index,j)" v-if="item.time_range.length==0" placeholder="请选择时间段"
                   style="width: 100%">
                 </TimePicker>
                 <TimePicker type="timerange" :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options format="HH:mm"
                   @on-change="weekAddTime($event,item,index,j)" v-if="item.time_range.length>0" :value="row.time"
                   placeholder="请选择时间段" style="width: 100%">
                 </TimePicker>

                 </Col>
                 <Col span="11">
                 <Input @on-keyup="weekAddAmount($event,item,index,j)" v-if="item.time_range.length==0" type="number"
                   placeholder="请设置场地费用"> <span slot="append">元/小时</span></Input>
                 <Input @on-keyup="weekAddAmount($event,item,index,j)" v-if="item.time_range.length>0"
                   :value="row.amount" type="number" placeholder="请设置场地费用"> <span
                   slot="append">元/小时</span></Input>

                 </Col>

                </Row>
              </div>
            </div>


          </div>

        </TabPane>

      </Tabs>


      <div slot="footer">
        <Button type="warning" @click="save('formValidate')" :disabled="isDisable" :loading="isLoading">保存</Button>
      </div>
    </Modal>

    <!-- 管理弹窗 -->
    <Modal v-model="detailModal" :title="detailTitle" width='1000' :footer-hide="true">
      <div class="detail-table">
        <div class="base-info">
          <Row>
            <Col class='row-main-title padding10 table-head-bg' span="2">门店名称</Col>
            <Col class="padding10" span="8">{{formValidate.store_name}} </Col>
            <Col class='row-main-title padding10 table-head-bg' span="2">球场名称</Col>
            <Col class="padding10" span="3">{{formValidate.name}}</Col>
            <Col class='row-main-title padding10 table-head-bg' span="2">场地数量</Col>
            <Col class="padding10" span="2">{{formValidate.num}}</Col>

          </Row>
          <Row>
            <Col class="padding10 table-head-bg row-main-title" span="2">费用</Col>
            <Col class="padding10" span="22">
             <div v-for="item in amountList">
               {{item.name}}&nbsp;&nbsp;
               <span v-for="it in item.value" >
               {{it.time}}(￥{{it.amount}}元/小时)&nbsp;&nbsp;</span>
             </div>
            </Col>
          </Row>
          <Row>
            <Col class="padding10 table-head-bg row-main-title" span="2">地址</Col>
            <Col class="padding10" span="22">{{formValidate.address}}</Col>
          </Row>
        </div>
      </div>

      <div>
        <Row>

          <Col span="24">
          <Tabs value="name1" v-model="name1" @on-click="hoverTab">
            <TabPane :label="item+'号场地'" :name="'name'+item" v-for="(item,index) in numberList">
              <Form :label-width="80">

                <FormItem label="选择日期" prop="date">
                  <DatePicker v-model="changeDate" @on-change="handleChange" type="date" placeholder="请选择日期"
                    format="yyyy-MM-dd" style="width: 250px"></DatePicker>
                </FormItem>


                <FormItem label="预约时段">

                  <div style="width: 480px;" class="make-list">
                    <span v-for="(it,index) in data.make_range">
                      <Tag :color="it.is_make==1?'default':'success'" style="width:110px;font-size: 16px;padding: 0;">
                        {{it.num}}</Tag>

                    </span>
                  </div><br>
                  <Alert>PS:绿色表示该时段未被用户预约、灰色表示该时段已被用户预约</Alert>
                </FormItem>

                <FormItem label="场地状态">
                  <i-switch v-model="data.venue_number.status" true-color="#FF9F60"
                    @on-change="updateStatus(data.venue_number)" size="large">
                    <span slot="open">开启</span>
                    <span slot="close">关闭</span>
                  </i-switch>

                </FormItem>

              </Form>
            </TabPane>
          </Tabs>
          </Col>
        </Row>
      </div>

    </Modal>

    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该数据吗？
      </p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>


  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'

  // 接口
  import {
    getList,
    add,
    put,
    del,
    getMakeData,
    updateStatus,
    storeVenueNumber,
    getVenueAmount
  } from '@/api/store-group/venue'
  import {
    tableOption
  } from '../../../data/store-group/venue.js'
  import Tables from '_c/tables'
  import {
    uploadImgPathList
  } from '@/config/global.js'
  // 上传组件
  import UploadTool from '../../components/uploadTool/uploadTool.vue'

  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {
      let _this = this
      this.$nextTick(function() {

        // 权限校验
        _this.role_add = permission(this.roles, 'store/add')
        _this.role_edit = permission(this.roles, 'store/edit')
        _this.role_del = permission(this.roles, 'store/delete')

      })
      this.formatDate()
      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({

        roles: state => state.user.roles

      }),
    },
    data() {
      return {

        // 权限标识
        role_add: false,
        role_edit: false,
        role_del: false,
        name1: 'name1',
        veneuAmount:'veneu1',
        setNumber: '',
        batchLen:1,
        len: 1,
        // 上传
        tableOption: tableOption,
        delId: '',
        data: {
          categoryList: [],

          list: [],
          storeList: [],
          venue_number: [],
          make_range: []
        },
        detailModal: false,
        detailTitle: '场地管理',
        createTitle: ' ',
        isAdd: true, // 新增true,修改false
        isDisable: false, // 新增时提交按钮点击状态
        isLoading: false, // 新增时提交按钮loading状态
        changeDate: '', //选择的日期
        loadingText: '',
        tableData: [],
        // 查询参数
        searchObj: {
          name: ''

        },
        // 分页
        page: {
          pageSize: 8,
          current: 1,
          total: 0
        },
        amountList: [],
        numberList: [], //门店已设置的所有场地编号
        // 分页end
        // 弹窗状态
        createModal: false, // 新增，修改弹窗
        delModal: false, // 删除弹窗
        changeNumber: 0, //选中的场地编号
        formValidate: {
          store_id: 0,
          name: '',
          status: '1',
          num: [1],
          amount: [],
          category_id: [],
          time: [],


        },

        ruleValidate: {
          store_id: [{
            required: true,
            message: '请选择门店',
            trigger: 'change',
            type: 'number'
          }],
          name: [{
            required: true,
            message: '请输入球场名称',
            trigger: 'blur'
          }],
          category_id: [{
            required: true,
            message: '请勾选场地分类',
            trigger: 'blur'
          }],
          // amount: [{
          //   required: true,
          //   message: '请输入场地费用',
          //   trigger: 'blur'
          // }]
        },
        weekArr:[],

        //批量数组
        batchArr:[],
        batchAmount:[],
        batchTime:[]
      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let params = {
          page: this.page.current,
          size: this.page.size,
          name: this.searchObj.name
        }

        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
            _this.data.storeList = result.storeList
            _this.data.categoryList = result.categoryList
          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      //获取当前时间
      formatDate() {
        let year = new Date().getFullYear()
        let month = new Date().getMonth() + 1
        let day = new Date().getDate()
        this.changeDate = year.toString() + '-' + month.toString() + '-' + day.toString()


      },
      detail(row) {
        this.detailModal = true;
        this.formValidate = JSON.parse(JSON.stringify(row))
        this.formValidate.amount = [];
        this.formValidate.time = [];
        this.formValidate.number = [];
        let tempArr = this.formValidate.category_id.split(',');
        this.formValidate.category_id = [];
        for (var i in tempArr) {
          this.formValidate.category_id.push(parseInt(tempArr[i]));
        }

        this.changeNumber = 0;
        this.formatDate();
        this.getMakeData();
      },
      getMakeData() {

        let _this = this
        let params = {
          store_id: this.formValidate.store_id,
          class_id: this.formValidate.id,
          number: this.changeNumber,
          changeDate: this.changeDate
        }

        getMakeData(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.make_range = result.make_range
            _this.data.venue_number = result.venue_number
            _this.data.venue_number.status = result.venue_number.status == 1 ? true : false
            _this.amountList = result.amountList;
            _this.numberList = result.numberList
            _this.name1 = 'name' + result.venue_number.number

          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      changepage(e) {
        this.page.current = e
        this.getList()
      },


      // 新增
      create() {
        if (!this.role_add) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }

        this.createModal = true
        //清空初始化数据
        this.weekArr = this.returnWeekArr();

        this.veneuAmount='veneu1',
        this.batchLen = 1 ;
        this.createTitle = '新增场地'
        this.isAdd = true
        this.formValidate = {} // 表单重置
        this.formValidate.status = '1';
        this.formValidate.amount = [];
        this.formValidate.time = [];
        this.formValidate.number = [];
        this.formValidate.store_id = 0

        this.$forceUpdate();

        this.handleReset('formValidate') // 验证重置
      },
      // 修改
      edit(row) {
        if (!this.role_edit) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.veneuAmount='veneu1',
        this.weekArr = this.returnWeekArr();
        this.batchLen = 1;
        this.createModal = true
        this.createTitle = '编辑场地'
        this.isAdd = false
        this.formValidate = {} // 表单重置
        this.formValidate = JSON.parse(JSON.stringify(row))
        this.formValidate.status = this.formValidate.status.toString();
        this.formValidate.num = this.formValidate.num.toString();
        let tempArr = this.formValidate.category_id.split(',');
        this.formValidate.category_id = [];
        for (var i in tempArr) {
          this.formValidate.category_id.push(parseInt(tempArr[i]));
        }
        this.formValidate.amount = [];
        this.formValidate.time = [];

        this.getStoreVenueNumber();
        this.getVenueAmount();
        this.handleReset('formValidate') // 验证重置
      },

      // 删除
      del(row) {
        if (!this.role_del) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.delId = row.id
        this.delModal = true
        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {

            _this.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      // 刷新
      refresh() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 重置
      reset() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 查询
      search() {
        this.getList()
      },

      save(name) {

        let _this = this

        this.$refs[name].validate((valid) => {
          if (valid) {
            if (_this.isAdd) {
              if (_this.formValidate.number.length <= 0) {
                this.$Message.error('请设置场地编号!')
                return;
              }

              for(var i in _this.weekArr){
                if (_this.weekArr[i].time_range.length<=0) {
                  this.$Message.error('请设置场地费用和时间!')
                  return;
                }
              }

              // 新增
              let obj = {
                name: _this.formValidate.name,
                number: _this.formValidate.number,
                status: _this.formValidate.status,
                store_id: _this.formValidate.store_id,
                category_id: _this.formValidate.category_id,
                weekArr:_this.weekArr
              }

              // 新增接口
              add(obj).then(res => {
                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.batchLen = 1;
                  _this.$Message.success('操作成功')


                } else {
                  _this.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                // _this.createModal = false
                console.log(error)
              })
            } else {
              // 修改

              let obj = {
                id: _this.formValidate.id,
                name: _this.formValidate.name,
                number: _this.formValidate.number,
                status: _this.formValidate.status,
                store_id: _this.formValidate.store_id,
                category_id: _this.formValidate.category_id,
                weekArr:_this.weekArr
              }

              // 修改接口
              put(obj).then(res => {
                if (res.data.status == 1) {
                  _this.batchLen = 1;

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                }
              }).catch(function(error) {
                // 异常
                console.log(error)
              })
            }

          } else {
            this.$Message.error('请输入必填项!')
          }
        })
      },
      handleReset(name) {
        this.$refs[name].resetFields()
      },
      handleChange(date) {

        this.changeDate = date
        this.getMakeData();
      },
      hoverTab(name) {

        let date = new Date(this.changeDate);
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        this.changeDate = year.toString() + '-' + month.toString() + '-' + day.toString()

        this.changeNumber = name.substr(4) //截取场地编号
        this.getMakeData();
      },
      updateStatus(item) {
        let _this = this

        let obj = {
          id: item.id,
          status: item.status
        }
        updateStatus(obj).then(res => {

          if (res.data.status == 1) {
            _this.getList() // 重新刷新数据
            _this.$Message.success('操作成功')
          } else {

          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },

      //设置场地编号
      setVenueNumber() {
        if (this.formValidate.store_id <= 0 || this.formValidate.store_id == undefined) {
          this.$Message.error('请先选择门店')
          return;
        }

        if (this.setNumber == '' || this.setNumber <= 0) {
          this.$Message.error('请输入场地编号且不能是0')
          return;
        }


        if (this.numberList.indexOf(parseInt(this.setNumber)) >= 0) {
          this.$Message.error('该编号已经被其他场地使用')
          return;
        }

        if (this.formValidate.number.indexOf(this.setNumber.toString()) < 0) {
          this.formValidate.number.push(this.setNumber);
          this.setNumber = '';
        }

      },

      delVenueNumber(num) {

        let i = this.formValidate.number.indexOf(num.toString())
        this.formValidate.number.splice(i, 1);
        this.$forceUpdate();

      },
      getStoreVenueNumber() {
        if (this.formValidate.store_id <= 0 || this.formValidate.store_id == undefined) {

          return;
        }
        let _this = this
        let obj = {
          store_id: this.formValidate.store_id
        }
        storeVenueNumber(obj).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.numberList = result.numberList

          } else {

          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      getVenueAmount() {
        let _this = this
        let obj = {
          class_id: this.formValidate.id
        }
        getVenueAmount(obj).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.weekArr = result.weekArr

          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      //批量添加
      batchInsert(){
        this.batchLen++;
      },
      //批量设置
      batchSet(){

        for(var i in this.weekArr){
          this.batchTime.forEach((value,j)=>{
            let data =   {
                   time:value,
                   amount:this.batchAmount[j]
                }

                if(this.weekArr[i]!=undefined){

                   this.weekArr[i].time_range.push(data);
                }

          })
        }
      },
      batchAddTime(e,i){
         this.batchTime[i] = e

      },
      batchAddAmount(e,i){
        this.batchAmount[i] = e.target.value
      },
      //单个添加
      weekInsert(item,i){

        let data ={
          time:[],
          amount:''
        }
        item.time_range.push(data);
        this.weekArr[i]=item;
      },
      weekAddTime(e,item,i,j){
        item.time_range[j].time = e
         this.weekArr[i]=item;
      },
      weekAddAmount(e,item,i,j){

        item.time_range[j].amount = e.target.value
         this.weekArr[i]=item;
      },
      returnWeekArr(){
        let tempWeekArr=[
          {
            name:'周一',
            week:1,
            time_range:[]
          },
          {
            name:'周二',
            week:2,
            time_range:[]
          },
          {
            name:'周三',
            week:3,
            time_range:[]
          },
          {
            name:'周四',
            week:4,
            time_range:[]
          },
          {
            name:'周五',
            week:5,
            time_range:[]
          },
          {
            name:'周六',
            week:6,
            time_range:[]
          },
          {
            name:'周日',
            week:7,
            time_range:[]
          },

        ];
        return tempWeekArr;
      }
    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
